package com.stacktry.funtv.utils;

import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.zip.GZIPInputStream;


public class HttpUtil {
	
	private static HttpUtil instance = new HttpUtil();
	
	public static HttpUtil getInstance(){
		return instance;
	}
	
	public void sendGetRequest(String url,HttpCallBack httpCallBack){
		RequestThread requestThread = new RequestThread(url, httpCallBack);
		requestThread.start();
	}
    
    class RequestThread extends Thread{
    	private String mUrl;
    	private HttpCallBack mHttpCallBack;
    	
    	public RequestThread(String url, HttpCallBack httpCallBack){
    		this.mUrl = url;
    		this.mHttpCallBack = httpCallBack;
    	}
    	
		@Override
		public void run() {
			//the response content reading input stream
			InputStream in = null;
			ByteArrayOutputStream baos = null;
			HttpURLConnection conn = null;
			try{
				//prepare the url connection
				URL url = new URL(mUrl);

				conn = (HttpURLConnection)url.openConnection();
				conn.setRequestMethod("GET");
				conn.setInstanceFollowRedirects(true);
				conn.setConnectTimeout(15000);
				conn.setReadTimeout(20000);
				
				conn.setRequestProperty("Accept-Encoding", "gzip,deflate");
				conn.setRequestProperty("Connection", "Close");
				
				//get the response code and message
				int code = conn.getResponseCode();
				String msg = conn.getResponseMessage();
				String encoding = conn.getContentEncoding();
				//read the response content
				if(encoding!=null && encoding.toLowerCase().matches("gzip")){
					in = new GZIPInputStream(new BufferedInputStream(conn.getInputStream()));
				}else{
					in = new BufferedInputStream(conn.getInputStream());
				}
				
				//for read response content from remote host
				byte[] buf = new byte[16*1024];
				baos = new ByteArrayOutputStream();
				
				//read the response content
				int sz = in.read(buf);
				while(sz != -1){
					baos.write(buf, 0, sz);
					sz = in.read(buf);
				}
				
				//make the response object
				mHttpCallBack.onSuccess(new HttpResponse(code, msg, baos.toByteArray()));
			}catch(Exception e){
				e.printStackTrace();
				mHttpCallBack.onFailer(0, e.getMessage());
			}finally{
				try{
					if(in != null){
						in.close();
					}
					if(baos != null){
						baos.close();
					}
					//close the connection
					conn.disconnect();
				}catch(Exception e){}
			}
		}
    
    }
      
    public interface HttpCallBack{
     void onSuccess(HttpResponse httpResponse);
     void onFailer(int code, String errorMsg);
    }
    
}
